<template>
  <div id="spaceDetailPage">
    <!-- 空间信息 -->
    <a-flex justify="space-between" style="margin-left: 100px; margin-right: 100px">
      <h2 v-if="canViewPicture">{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
      <a-space size="middle">
        <!-- 主色调搜索 -->
        <a-form-item label="主色调相似匹配" style="margin-top: 23px" title="匹配主色调相似的图片" v-if="canViewPicture">
          <color-picker format="hex" @pureColorChange="onColorChange" />
        </a-form-item>
        <a-button
          v-if="canUploadPicture"
          type="primary"
          :href="`/upload_picture_to_my_space?spaceId=${space.id}`"
          :icon="h(CloudUploadOutlined)"
          title="上传新图片至云"
          >上传新图
        </a-button>
        <a-button
          v-if="canManageSpaceUser"
          :href="`/spaceUserManage/${id}`"
          type="primary"
          ghost
          target="_blank"
          :icon="h(UserSwitchOutlined)"
          title="管理空间成员、编辑权限信息"
          >成员管理
        </a-button>
        <a-button
          v-if="canManageSpaceUser"
          :href="`/space_analyze?spaceId=${space.id}`"
          type="primary"
          ghost
          :icon="h(BarChartOutlined)"
          title="对空间数据进行综合分析"
          >空间分析
        </a-button>
        <a-button
          v-if="canEditPicture"
          type="primary"
          ghost
          @click="doBatchEdit"
          :icon="h(EditOutlined)"
          title="批量编辑图片（仅对当前页面展示图片生效）"
        >
          批量编辑
        </a-button>
        <a-button
          v-if="canManageSpaceUser"
          type="primary"
          ghost
          :href="`/edit_space?id=${space.id}`"
          :icon="h(EditOutlined)"
          title="编辑云空间信息"
        >
          编辑云
        </a-button>
        <a-popover trigger="hover" placement="top" :color="'black'">
          <template #content>
            <div :style="{ color: 'white' }">
              已使用容量：{{ formatSize(space.totalSize) }} /
              {{ formatSizeNoDecimalFraction(space.maxSize) }}
            </div>
            <div :style="{ color: 'white' }">
              已使用 {{ ((space.totalSize / space.maxSize) * 100).toFixed(4) }} % 的空间
            </div>
            <div :style="{ color: 'white' }">
              已上传图片：{{ total }} 张 / {{ space.maxCount }} 张
            </div>
            <div :style="{ color: 'white' }">
              可上传图片： {{ space.maxCount - space.totalCount }} 张
            </div>
          </template>
          <template #title>
            <div :style="{ color: 'white' }">
              {{ space.spaceType === SPACE_TYPE_ENUM.PRIVATE ? '个人云' : '团队云' }}使用情况：
            </div>
          </template>
          <a-progress
            v-if="canViewPicture"
            type="circle"
            :size="70"
            :percent="((space.totalSize * 100) / space.maxSize).toFixed(2)"
          />
        </a-popover>
      </a-space>
    </a-flex>
    <!-- 图片搜索表单 -->
    <picture-search-form :onSearch="doSearch" :onClearBatchEditForm="clearBatchForm" />
    <div style="margin-bottom: 27px" />
    <!-- 图片列表 -->
    <picture-list
      :dataList="dataList"
      :spaceId="space.id"
      :loading="loading"
      :onReload="fetchData"
      :canEdit="canEditPicture"
      :canDelete="canDeletePicture"
      :publicFlag="publicFlag"
    />
    <template></template>
    <a-pagination
      style="text-align: center"
      show-quick-jumper
      v-model:current="searchParams.current"
      v-model:pageSize="searchParams.pageSize"
      :page-size-options="pageSizeOptions"
      :total="total"
      :show-total="showTotal"
      @change="onPageChange"
    />
    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :spaceId="space.id as number"
      :pictureList="dataList"
      :onSuccess="batchEdit"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, h, watch, computed } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import {
  EditOutlined,
  CloudUploadOutlined,
  BarChartOutlined,
  UserSwitchOutlined,
} from '@ant-design/icons-vue'
import { useRoute } from 'vue-router'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController.ts'
import PictureList from '@/components/PictureList.vue'
import { formatSize, formatSizeNoDecimalFraction } from '@/utils'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_ENUM, SPACE_TYPE_MAP } from '../constants/space.ts'

const props = defineProps<{
  id: string | number
}>()

const space = ref<API.SpaceVO>({ id: 0 })

const publicFlag = ref<boolean>(false)

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)
const canViewPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_VIEW)

/**
 * 跳转后，根据id获取空间详情数据
 */
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({
      // @ts-ignore
      id: props.id,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('抱歉，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败，' + e.message)
  }
}

// 首次进入空间详情页，加载数据
onMounted(() => {
  fetchSpaceDetail()
})

// 获取图片列表
const route = useRoute()

// 定义数据类型
const dataList = ref<API.PictureVO[]>([])
// 分页数据总数
const total = ref(0)
// 定义搜索条件
const searchParams = ref<API.PictureQueryRequest>({
  // @ts-ignore
  searchText: route.query.searchText,
  // @ts-ignore
  category: route.query.category,
  // @ts-ignore
  tags: route.query.tags,
  current: 1,
  pageSize: 18,
  sortField: '',
  sortOrder: 'descend',
})
const loading = ref(true)

// 根据搜索条件，远程获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    ...searchParams.value,
    spaceId: props.id,
  }
  // @ts-ignore
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取图片数据失败，' + res.data.message)
  }
  loading.value = false
}

// 首次进入图片管理页面，请求一次默认搜索的图片数据
onMounted(() => {
  fetchData()
})

/**
 * 搜索图片
 */
const doSearch = (newSearchParams: API.PictureQueryRequest) => {
  // 搜索后回到第一页
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
  }
  searchParams.value.current = 1
  fetchData()
}

// 展示总条数
// @ts-ignore
const showTotal = (total) => `共 ${total} 张`
// 定义分页器参数
const onPageChange = (page: number, pageSize: number) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}
// 定义每页数据量操作选项
const pageSizeOptions = ref<string[]>(['10', '18', '20', '30', '40', '50'])

/**
 * 主色调搜索相似图片
 * @param color
 */
const onColorChange = async (color: string) => {
  loading.value = true
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    // @ts-ignore
    spaceId: props.id,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data.length
    message.success('匹配主色调相似图片成功，至多匹配18张图片')
  } else {
    message.error('匹配失败，' + res.data.message)
  }
  loading.value = false
}

// 批量编辑当前页面图片
const batchEditPictureModalRef = ref()
// 批量编辑图片成功
const batchEdit = () => {
  // 父组件刷新数据
  fetchData()
}
// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}
// 清空批量编辑表单输入
const clearBatchForm = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.clearForm()
  }
}

// 空间ID改变时，必须重新获取数据
watch(
  () => props.id,
  () => {
    fetchSpaceDetail()
    fetchData()
  },
)
</script>

<style scoped></style>
